package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.BuyRecord;
import cn.wolfcode.crm.domain.Customer;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemDictionaryItem;
import cn.wolfcode.crm.qo.BuyRecordQueryObject;
import cn.wolfcode.crm.qo.JsonResult;
import cn.wolfcode.crm.service.IBuyRecordService;
import cn.wolfcode.crm.service.ICustomerService;
import cn.wolfcode.crm.service.ISystemDictionaryItemService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@RequestMapping("buyRecord")
@Controller
public class BuyRecordController {

	@Autowired
	private IBuyRecordService buyRecordService;

	@Autowired
	private ICustomerService customerService;

	@Autowired
	private ISystemDictionaryItemService systemDictionaryItemService;
	
	@RequestMapping("list")
	public String list(Model model, @ModelAttribute("qo")BuyRecordQueryObject qo){
		// 当前登录用户
		Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
		// 不是超级管理员或者不是市场经理只能看自己跟踪的客户
		if (!(employee.isAdmin() || SecurityUtils.getSubject().hasRole("Market_Manager"))) {
			qo.setSellerId(employee.getId());
		} else { // 是超级管理员和市场经理才查询所有销售人员，回显在页面
			// 若是普通市场专员都没有这个功能，就没浪费数据查询了

		}
		//int i = 1/0;
		PageInfo<BuyRecord> pageInfo = buyRecordService.query(qo);
		model.addAttribute("pageInfo",pageInfo);
		//用户
		List<Customer> customers = customerService.selectByStatus(0);
		model.addAttribute("customers", customers);

		//课程
		List<SystemDictionaryItem> courses = systemDictionaryItemService.selectBySystemDictionarySn("course");
		model.addAttribute("courses", courses);

		return "buyRecord/list";
	}
	
	/*@RequestMapping("input")
	@RequriedPermission(name="部门编辑",expression = "buyRecord:input")
	public String input(Long id,Model model){
		if (id!=null) {
			BuyRecord buyRecord = buyRecordService.select(id);
			model.addAttribute("buyRecord", buyRecord);
		}
		return "buyRecord/input";
	}*/
	

	@RequestMapping("saveOrUpdate")
	@ResponseBody
	public JsonResult saveOrUpdate(BuyRecord buyRecord){

		try {
			if (buyRecord.getId()!=null) {
				buyRecordService.update(buyRecord);
			}else {
				buyRecordService.insert(buyRecord);
			}
			return new JsonResult(true,"新增或修改成功");
		}catch (Exception e){
			e.printStackTrace();
			return new JsonResult(false,"新增或修改失败");
		}

	}
}
